package com.nf.db.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 由于此类是一个工具性质的类，按照大家的习惯
 * 工具类里面基本都是静态方法，而且工具类通常不会有子类
 * 所以工具类一般应该添加一个final修饰符，防止它有子类
 * <p>
 * 工具类一般不会实例化，所以其构造函数应该不允许使用者访问，
 * 所以构造函数一般设置为私有
 */
public final class CleanerUtils {
    private CleanerUtils() {
    }

    public static void close(Connection con) throws SQLException {
        if (con != null) {
            con.close();
        }
    }

    public static void close(PreparedStatement pstmt) throws SQLException {
        if (pstmt != null) {
            pstmt.close();
        }
    }

    public static void close(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }

    public static void closeQuietly(Connection con) {
        try {
            close(con);
        } catch (SQLException e) {
            //quiet
        }
    }

    public static void closeQuietly(PreparedStatement pstmt) {
        try {
            close(pstmt);
        } catch (SQLException e) {
            //quiet
        }
    }

    public static void closeQuietly(ResultSet rs) {
        try {
            close(rs);
        } catch (SQLException e) {
            //quiet
        }
    }

    /**
     * 一次关闭三个对象，通常会用在查询操作里
     *
     * @param rs
     * @param pstmt
     * @param conn
     */
    public static void closeQuietly(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        try {
            closeQuietly(rs);
        } finally {
            try {
                closeQuietly(pstmt);
            } finally {
                closeQuietly(conn);
            }
        }
    }


    /**
     * 关闭2个对象，通常用在增删改操作里
     *
     * @param pstmt
     * @param conn
     */
    public static void closeQuietly(PreparedStatement pstmt, Connection conn) {
        try {
            closeQuietly(pstmt);
        } finally {
            closeQuietly(conn);
        }
    }

}
